<template>
    <div class="content">
        <el-card>
            <el-form class="form" label-width="100px">
                <el-row>
                    <el-col :span="3">
                        <el-form-item label="产品信息">
                            <RiskEntryInput
                                :url="'/ledger/fundInfo/list/byUser/like?fundCodeOrName='"
                                @set-entry-data="getEntryslist"
                                :itemKey="'fundProductCode'"
                                :returnDatas="searchParams.codeAndName"
                                class="item"
                                style="display: inline-block"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="产品状态">
                            <el-select v-model="searchParams.fundOptStatus" size="mini" class="item" clearable filterable>
                                <el-option v-for="(value, key) in fundOptStatusPojo" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="募集方式">
                            <el-select v-model="searchParams.fundType1" size="mini" class="item" clearable filterable @change="changeFundType1">
                                <el-option v-for="(value, key) in FundType1" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="产品类型">
                            <el-select
                                v-model="searchParams.fundType2"
                                size="mini"
                                class="item"
                                clearable
                                filterable
                                multiple
                                collapse-tags
                                @focus="focusFundeType2"
                            >
                                <el-option v-for="(value, key) in FundType2" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="是否QDII">
                            <el-select v-model="searchParams.isQDII" size="mini" class="item" clearable filterable>
                                <el-option key="1" value="1" label="是"></el-option>
                                <el-option key="0" value="0" label="否"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="是否FOF">
                            <el-select v-model="searchParams.isFof" size="mini" class="item" clearable filterable>
                                <el-option key="1" value="1" label="是"></el-option>
                                <el-option key="0" value="0" label="否"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label-width="15px">
                            <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                            <el-button size="mini" @click="handleBtn('pass')">批量复核</el-button>
                            <el-button size="mini" @click="handleBtn('layout')">布局设置</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <div class="table">
            <RiskTableP
                ref="risk-table"
                :tableConfig="tableConfig"
                :tableData="tableData"
                :column="actualShowFieldList"
                :paging="paging"
                :showTooltip="false"
                v-loading="tableLoading"
                style="height: 100%"
                @page-change="getTableData(false)"
                :key="tableKey + 'tableKey'"
            >
                <template #fdProductCode="{ row }">
                    <!-- <el-tooltip
                    :disabled="!row.hasOwnProperty('old' + 'fdProductCode')"
                    :content="'原：' + row['old' + 'fdProductCode']"
                    placement="bottom-start"
                > -->
                    <span>{{ row.fdProductCode || '--' }}</span>
                    <!-- </el-tooltip> -->
                </template>
                <template #fundNameSt="{ row }">
                    <!-- <el-tooltip
                    :disabled="!row.hasOwnProperty('old' + 'fundNameSt')"
                    :content="'原：' + row['old' + 'fundNameSt']"
                    placement="bottom-start"
                > -->
                    <span>{{ row.fundNameSt || '--' }}</span>
                    <!-- </el-tooltip> -->
                </template>
                <template #custom-slot="{ row, item }">
                    <el-tooltip
                        :disabled="!row.hasOwnProperty('old' + item.field)"
                        :content="'原：' + getColumnShowValue('old' + item.field, row)"
                        placement="bottom-start"
                    >
                        <span>{{ getColumnShowValue(item.field, row) || '--' }}</span>
                    </el-tooltip>
                </template>
                <template #operation="{ row }">
                    <RiskIconButton
                        type="primary"
                        icon="el-icon-document-checked"
                        topTitle="校验通过"
                        @on-click="handleBtnRow('pass', row)"
                    ></RiskIconButton>
                </template>
            </RiskTableP>
        </div>
        <!-- 布局设置 -->
        <RiskTableLayout
            title="产品设置页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="test-check-info10"
            @on-submit="onSubmit"
        />

        <yh-dialog
            drag
            :title="`确定校验通过以下产品信息吗？`"
            :visible.sync="verifyVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="700px"
        >
            <div v-if="checkRowKeys.length == 1">
                <h3>{{ `${currentRowData.fundNameSt}(${currentRowData.fdProductCode})` }}</h3>
                <EntryItemCompare v-if="editDatas.length" :data="editDatas" />
            </div>
            <div v-else>
                <span>{{ checkRowKeys.join(',') }}</span>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button @click="verifyVisible = false"> 取 消 </el-button>
                <el-button type="primary" @click="confirm('verify')"> 确 认 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { PageVO, TableConfigVO } from '@/common/vo';
import EntryItemCompare from '@/pages/setting/components/item-setting/item-compare.vue';
import { dateFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import * as api from '../api/fund-ledger-manage';
import DictionConstUtil from '../dict';

@Component({ name: 'FundCheck', components: { RiskTableP, RiskIconButton, RiskTableLayout, RiskEntryInput, EntryItemCompare } })
export default class FundCheck extends Vue {
    dateFormat = dateFormat;
    FundType1 = DictionConstUtil.FundType1;
    FundType2 = {};
    FUNDTYPE2 = DictionConstUtil.FUNDTYPE2;
    fundOptStatusPojo = DictionConstUtil.fundOptStatusPojo;
    yOrNOptions = DictionConstUtil.yOrNOptions;
    isExempt = {
        '0': '未豁免',
        '1': '豁免',
    };
    tableKey: number = -1;
    tableLoading: boolean = true;
    tableConfig: TableConfigVO = {
        rowKey: 'fdProductCode',
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [];
    tableDataAll: any[] = [];
    tableColumns: any = [
        { minWidth: '80px', field: 'fdProductCode', title: '产品代码' },
        { minWidth: '160px', field: 'fundNameSt', title: '产品简称' },
        { minWidth: '100px', field: 'fundOptStatus', title: '产品状态', align: 'center', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'fundType1', title: '募集方式', align: 'center', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'fundType2', title: '产品类型', align: 'center', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'setupDate', title: '成立日期', align: 'center', slotName: 'custom-slot' }, // dtCtTime
        // { minWidth: '100px', field: 'isBuildPosition', title: '是否建仓期', align: 'center', slotName: 'custom-slot' }, //
        // { minWidth: '100px', field: 'buildPosition', title: '建仓期', align: 'center', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'warnLine', title: '预警线', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'stopLossLine', title: '止损线', slotName: 'custom-slot' },
        {
            minWidth: '200px',
            field: 'yjzsxbjjzType',
            title: '预警、止损控制类型',
            slotName: 'custom-slot'
        },
        { minWidth: '100px', field: 'localCustodian', title: '托管行', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'localCustodianName', title: '托管行名称', slotName: 'custom-slot' },
        // { minWidth: '100px', field: 'overAdjustDays', title: '超限调整日期', slotName: 'custom-slot' }, //
        { minWidth: '100px', field: 'oneLevelStrategy', title: '一级策略', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'twoLevelStrategy', title: '二级策略', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'threeLevelStrategy', title: '三级策略', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'investManager', title: '投资经理', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'isQDII', title: '是否QDII', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'isFof', title: '是否FOF', slotName: 'custom-slot' },
        {
            minWidth: '100px',
            field: 'evaluationMethod',
            title: '估值方法',
            slotName: 'custom-slot',
        },
        {
            minWidth: '100px',
            field: 'productOptType',
            title: '运作方式',
            slotName: 'custom-slot',
        },
        { minWidth: '100px', field: 'openType', title: '开放期限', slotName: 'custom-slot' },
        { minWidth: '100px', field: 'riskLevel', title: '风险特征', slotName: 'custom-slot' },
        // {
        //     minWidth: '100px',
        //     field: 'double25Exempt',
        //     title: '双25%豁免',
        //     render: value => DictionConstUtil.yOrNOptions[value],
        //     slotName: 'custom-slot',
        // },
    ];

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };
    selectLoading: boolean = false;
    private issueCodeSelectList: any[] = []; // 发行人代码下拉框数据

    // 分发配置参数
    searchParams: any = {
        codeAndName: '',
        fundType1: [],
        fundOptStatus: '',
        fundType2: [],
        isQDII: '',
        isFof: '',
    };

    checkRowKeys: any = []; // 待处理勾选数据
    verifyVisible: boolean = false; // 校验弹框
    currentRowData: any = {};
    editDatas: any = [];
    layoutDialog: boolean = false;
    selectedFieldList: any[] = [];
    showFieldList: any[] = [];
    fixedFieldList: any[] = [
        { minWidth: '80px', field: 'fdProductCode', title: '产品代码' },
        { minWidth: '160px', field: 'fundNameSt', title: '产品简称' },
    ];

    // 实际展示字段
    get actualShowFieldList() {
        return [
            {
                type: 'checkbox',
                selectedAll: false,
                fixed: 'left',
                align: 'center',
                width: 60,
            },
            ...this.showFieldList,
            {
                title: '操作',
                field: 'operation',
                fixed: 'right',
                width: 80,
                align: 'center',
            },
        ];
    }
    firstVisit: boolean = true; // 首次访问
    @Prop() activeValue: string;
    @Watch('activeValue', { immediate: true })
    async handleActiveValue(newData, oldData) {
        if (newData == 'fund-check' && this.firstVisit) {
            this.firstVisit = false;
            this.tableColumns = this.tableColumns.map(item => {
                return { ...item, id: item.field, content: item.title };
            });
            this.fixedFieldList = this.fixedFieldList.map(item => {
                return { ...item, id: item.field, content: item.title };
            });
            await this.queryLayout();
            this.getTableData(false);
            this.getIssueCodeList('');
            this.getAllTableData();
        }
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/test-check-info10')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });

        if (resList) {
            this.selectedFieldList = [];
            const list = JSON.parse(resList) || [];
            list.forEach(item => {
                let obj = this.tableColumns.find(ele => ele.content === item.content); //
                if (obj) {
                    this.selectedFieldList.push(obj);
                }
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            console.log(this.showFieldList, 'showFeld--------');

            this.tableKey++;
        } else {
            this.showFieldList = this.tableColumns;
            this.selectedFieldList = this.tableColumns;
            this.tableKey++;
        }
    }

    /**
     * 表格数据
     */
    getTableData(reset: boolean) {
        this.tableLoading = true;
        return new Promise((resolve, reject) => {
            api.productCheckList({ ...this.searchParams, paging: this.paging })
                .then((res: any) => {
                    this.tableData = res.list || [];
                    this.paging.total = res.total;
                    reset && this.resetCheckRowKeys();
                    resolve(res);
                })
                .catch((err: any) => {
                    // const res = {
                    //     list: [
                    //         {
                    //             fdProductCode: '234',
                    //             fundNameSt: '招商证券股票星集合资产管理计划',
                    //             oldFundNameSt: '招商123',
                    //             fundType2: 'A',
                    //             oldfundType2: '空',
                    //         },
                    //         { fdProductCode: '254', fundNameSt: '招商证券股票星集合资产管理计划254' },
                    //     ],
                    //     total: 1,
                    // };
                    // this.tableData = res.list || [];
                    // this.paging.total = res.total;
                    reject(err);
                })
                .finally(() => {
                    this.tableLoading = false;
                });
        });
    }

    // 募集方式变动
    changeFundType1(value) {
        this.searchParams.fundType2 = [];
        if (value == '') {
            this.FundType2 = {};
        } else if (value == 'D') {
            this.FundType2 = DictionConstUtil.FundType3;
        } else if (['A', 'B'].includes(value)) {
            this.FundType2 = DictionConstUtil.FundType2;
        }
    }

    // 产品类型变动
    focusFundeType2() {
        if (this.searchParams.fundType1 == '') {
            this.yh_message_warn('先选择募集方式!');
            return;
        }
    }

    /**
     * 重置勾选
     */
    resetCheckRowKeys() {
        this.$nextTick(() => {
            (this.$refs['risk-table'] as any).resetCheckRowKeys();
        });
    }

    // 产品代码
    getEntryslist(val: any) {
        this.searchParams.codeAndName = val;
    }

    /**
     * 按钮点击
     */
    async handleBtn(type: string) {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData(true);
        } else if (type == 'pass') {
            this.editDatas = [];
            const checkRowKeys = (this.$refs as any)['risk-table'].checkRowKeys || [];
            if (checkRowKeys.length < 1) {
                this.yh_message_error('请先勾选需检验的产品');
                return;
            }
            if (checkRowKeys.length == 1) {
                const row = this.tableDataAll.find(ele => ele.fdProductCode == checkRowKeys[0]);
                this.handleBtnRow(type, row);
            }
            this.checkRowKeys = checkRowKeys;
            this.verifyVisible = true;
        } else if (type == 'layout') {
            this.layoutDialog = true;
        }
    }

    /**
     * 确认按钮点击
     */
    async confirm(type: string) {
        if (type == 'search') {
            await this.getTableData(true);
        } else if (type == 'verify') {
            const fun = api.differenceUpdate;
            fun({ checkFlag: '1', fdProductCodes: this.checkRowKeys })
                .then((res: any) => {
                    this.yh_message_success('检验通过');
                    this.getTableData(true);
                })
                .finally(() => {
                    this.verifyVisible = false;
                });
        }
    }

    /**
     * 布局设置
     */
    onSubmit() {
        this.queryLayout();
    }

    /**
     * 表格行按钮处理
     */
    handleBtnRow(type: string, row: any) {
        this.editDatas = [];
        this.currentRowData = row;
        this.checkRowKeys = [row.fdProductCode];
        // fundCodes: this.checkRowKeys,
        this.verifyVisible = true;
        api.productCheckDifference({ fdProductCode: row.fdProductCode }).then(res => {
            console.log(res, 'res');
            let data = [];
            const values: any = Object.values(res);
            // debugger;
            values.map(ele => {
                data = data.concat(ele);
            });
            console.log(data, 'data');

            this.editDatas = data;
        });
    }

    /**
     * 右侧的所有数据
     */
    getAllTableData() {
        api.productCheckList({
            paging: {
                currentPage: 1,
                pageSize: 10000,
            },
        })
            .then((res: any) => {
                this.tableDataAll = res.list;
            })
            .catch(err => {
                console.log(err);
            });
    }
    /**
     * 获取发行人代码下拉框数据
     */
    getIssueCodeList(e: string) {
        this.selectLoading = true;
        this.$axios
            .post('/dict/issue/select', {
                dictKey: e,
                dictKeyName: e,
            })
            .then((res: any) => {
                this.issueCodeSelectList = res || [];
                this.selectLoading = false;
            });
    }

    /**
     * 处理表格内容显示值
     */
    getColumnShowValue(field: string, row: any) {
        console.log('hzj11', field, row[field], ['yjzsxbjjzType', 'old' + 'yjzsxbjjzType'].includes(field))
        let name = row[field];
        if (name === '空') {
            return name;
        }
        if (field == 'fundOptStatus' || field == 'old' + 'fundOptStatus') {
            name = this.fundOptStatusPojo[row[field]];
        } else if (field == 'fundType1' || field == 'old' + 'fundType1') {
            name = this.FundType1[row[field]];
        } else if (field == 'fundType2' || field == 'old' + 'fundType2') {
            name = this.FundType2[row[field]];
            // 'buildPosition', 'old' + 'buildPosition'
        } else if (['setupDate', 'old' + 'setupDate'].includes(field)) {
            name = dateFormat(row[field]);
        } else if (
            [
                'isBuildPosition',
                'old' + 'isBuildPosition',
                'double25Exempt',
                'old' + 'double25Exempt',
                'isQDII',
                'old' + 'isQDII',
                'isFof',
                'old' + 'isFof',
            ].includes(field)
        ) {
            name = this.yOrNOptions[row[field]] ? this.yOrNOptions[row[field]] : '';
        } else if (['evaluationMethod', 'old' + 'evaluationMethod'].includes(field)) {
            name = DictionConstUtil.evaluationMethodPojo[row[field]] ? DictionConstUtil.evaluationMethodPojo[row[field]] : '';
        } else if (['productOptType', 'old' + 'productOptType'].includes(field)) {
            name = DictionConstUtil.productOptTypePojo[row[field]] ? DictionConstUtil.productOptTypePojo[row[field]] : '';
        } else if (['openType', 'old' + 'openType'].includes(field)) {
            name = DictionConstUtil.openTypePojo[row[field]] ? DictionConstUtil.openTypePojo[row[field]] : '';
        } else if (['riskLevel', 'old' + 'riskLevel'].includes(field)) {
            name = DictionConstUtil.riskLevelPojo[row[field]] ? DictionConstUtil.riskLevelPojo[row[field]] : '';
        } else if (['yjzsxbjjzType', 'old' + 'yjzsxbjjzType'].includes(field)) {
            name = DictionConstUtil.yjzsxbjjzTypePojo[row[field]] ? DictionConstUtil.yjzsxbjjzTypePojo[row[field]] : '';
        }
        return name;
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    background-color: #fff;
    .form {
        // display: grid;
        // grid-template-columns: repeat(4, 1fr) 278px;
        // // border: 1px solid #ccc;
        // // padding: 8px;
        // // margin-bottom: 10px;
        // .el-form-item {
        //     margin-bottom: 0px;
        // }
        // .item {
        //     width: 70%;
        //     /deep/ .el-select {
        //         width: 100%;
        //     }
        // }
    }
    .table {
        padding: 10px;
        margin-top: 10px;
        height: calc(100% - 110px);
        background-color: #fff;
    }
    .form-search {
        display: grid;
        grid-template-columns: 1fr 1fr;
        .el-form-item {
            margin-bottom: 10px;
        }
        .item {
            width: 100%;
        }
    }

    .dialog-footer {
        text-align: right;
        margin-right: 10px;
    }
}

/deep/ span.el-tag.el-tag--info.el-tag--mini.el-tag--light {
    display: flex;
    align-items: center;
    width: 74%;
    max-width: fit-content;
    padding: 0px;
    margin: 2px 0 2px 2px;
    .el-select__tags-text {
        display: inline-block;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

/deep/ .el-select {
    .el-select__tags {
        flex-wrap: nowrap;
    }
    .el-tag__close.el-icon-close {
        right: 1px;
    }
}
/deep/ .el-form-item {
    margin-bottom: 0px;
}
</style>
